﻿using Dapper;
using Dapper.Contrib.Extensions;
using Gx.Common.Core;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using Dapper;
using Dapper.Contrib.Extensions;

namespace Gx.Dal
{
    /// <summary>
    /// 数据库访问基类
    /// </summary>
    /// <typeparam name="T">实体类类型</typeparam>
    public partial class BaseDal<T> where T : class
    {
        /// <summary>
        /// 对象的表名
        /// </summary>
        public string TableName { get; set; }

        /// <summary>
        /// 主键属性对象
        /// </summary>
        public PropertyInfo PrimaryKey { get; set; }

        public BaseDal()
        {
            this.TableName = EntityHelper.GetTableName(typeof(T));
            //this.PrimaryKey = EntityHelper.GetSingleKey<T>();
        }

        ///// <summary>
        ///// 数据库连接
        ///// </summary>
        //protected IDbConnection Connection
        //{
        //    get
        //    {
        //        var connection = new DbContext().Connection;
        //        connection.Open();
        //        return connection;
        //    }
        //}

        /// <summary>
        /// 返回数据库所有的对象集合
        /// </summary>
        /// <returns></returns>
        public IEnumerable<T> GetAll()
        {
            using (var dbcontext = new DbContext())
            {
                string query = string.Format("SELECT * FROM {0} WITH(NOLOCK) WHERE IsDeleted=0", TableName);
                return dbcontext.Connection.Query<T>(query);
            }
        }
        public IEnumerable<T> GetListByWhere(string condition, object param = null)
        {
            using (var dbcontext = new DbContext())
            {
                string where = string.IsNullOrWhiteSpace(condition) ? "" : " AND " + condition;
                string query = string.Format("SELECT * FROM {0} WITH(NOLOCK) WHERE IsDeleted=0 {1}", TableName, where);
                return dbcontext.Connection.Query<T>(query, param);
            }
        }


        /// <summary>
        /// 查询数据库,返回指定ID的对象
        /// </summary>
        /// <param name="id">主键的值</param>
        /// <returns></returns>
        public T Get(object id)
        {
            using (var dbcontext = new DbContext())
            {
                return dbcontext.Connection.Get<T>(id);
            }
        }

        /// <summary>
        /// 插入指定对象到数据库中
        /// </summary>
        /// <param name="info">指定的对象</param>
        /// <returns></returns>
        public bool Insert(T info)
        {
            bool result = false;
            using (var dbcontext = new DbContext())
            {
                var id = dbcontext.Connection.Insert(info);
                result = true;
            }
            return result;
        }

        public long InsertAnGetId(T info)
        {
            using (var dbcontext = new DbContext())
            {
                var id = dbcontext.Connection.Insert(info);
                return id;
            }
        }
        /// <summary>
        /// 插入指定对象集合到数据库中
        /// </summary>
        /// <param name="list">指定的对象集合</param>
        /// <returns></returns>
        public bool Insert(IEnumerable<T> list)
        {
            bool result = false;
            using (var dbcontext = new DbContext())
            {
                result = dbcontext.Connection.Insert(list) > 0;
            }
            return result;
        }

        /// <summary>
        /// 更新对象属性到数据库中
        /// </summary>
        /// <param name="info">指定的对象</param>
        /// <returns></returns>
        public bool Update(T info)
        {
            bool result = false;
            using (var dbcontext = new DbContext())
            {
                result = dbcontext.Connection.Update(info);
            }
            return result;
        }
        /// <summary>
        /// 更新指定对象集合到数据库中
        /// </summary>
        /// <param name="list">指定的对象集合</param>
        /// <returns></returns>
        public bool Update(IEnumerable<T> list)
        {
            bool result = false;
            using (var dbcontext = new DbContext())
            {
                result = dbcontext.Connection.Update(list);
            }
            return result;
        }
        /// <summary>
        /// 从数据库中删除指定对象
        /// </summary>
        /// <param name="info">指定的对象</param>
        /// <returns></returns>
        public bool Delete(T info)
        {
            bool result = false;
            using (var dbcontext = new DbContext())
            {
                result = dbcontext.Connection.Delete(info);
            }
            return result;
        }
        /// <summary>
        /// 从数据库中删除指定对象集合
        /// </summary>
        /// <param name="list">指定的对象集合</param>
        /// <returns></returns>
        public bool Delete(IEnumerable<T> list)
        {
            bool result = false;
            using (var dbcontext = new DbContext())
            {
                result = dbcontext.Connection.Delete(list);
            }
            return result;
        }
        /// <summary>
        /// 根据指定对象的ID,从数据库中删除指定对象
        /// </summary>
        /// <param name="id">对象的ID</param>
        /// <returns></returns>
        public bool DeleteById(object id)
        {
            bool result = false;
            using (var dbcontext = new DbContext())
            {
                //string query = string.Format("DELETE FROM {0} WHERE {1} = @id", TableName, PrimaryKey.Name);
                string query = string.Format("UPDATE {0} SET IsDeleted=1 WHERE Id = @id", TableName);
                var parameters = new DynamicParameters();
                parameters.Add("@id", id);

                result = dbcontext.Connection.Execute(query, parameters) > 0;
            }
            return result;
        }

        public bool DeleteByIds<TType>(List<TType> ids)
        {
            bool result = false;
            using (var dbcontext = new DbContext())
            {
                //string query = string.Format("DELETE FROM {0} WHERE {1} = @id", TableName, PrimaryKey.Name);
                string query = string.Format("UPDATE {0} SET IsDeleted=1 WHERE Id in @ids", TableName);
                var parameters = new DynamicParameters();
                parameters.Add("@ids", ids);

                result = dbcontext.Connection.Execute(query, parameters) > 0;
            }
            return result;
        }
        /// <summary>
        /// 从数据库中删除所有对象
        /// </summary>
        /// <returns></returns>
        public bool DeleteAll()
        {
            bool result = false;
            using (var dbcontext = new DbContext())
            {
                result = dbcontext.Connection.DeleteAll<T>();
            }
            return result;
        }


        public bool UseTransaction(Func<IDbConnection, IDbTransaction, bool> func)
        {
            using (var dbcontext = new DbContext())
            {
                var conn = dbcontext.Connection;
                using (IDbTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        var obj = func(conn, trans);
                        trans.Commit();
                        return obj;
                    }
                    catch (Exception)
                    {
                        trans.Rollback();
                        conn.Close();
                        throw;
                    }
                }
            }
        }

        
    }


    
}
